package com.alibaba.citrus.cr.sales.plan.repository;

import com.alibaba.citrus.cr.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.exception.RepositoryException;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.SalesPlanQueryService;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.SalesPlanWriteService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryAdjustmentDetailsRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryNotificationConfigRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryPlanScItemStatRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQuerySalePlanRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QuerySalesPlanRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanScItemPageQueryRequest;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesPlanModelEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesPlanStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.features.SalesPlanFeatures;
import com.alibaba.citrus.cr.sales.plan.sdo.MonthlyPlanDataSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.NotificationConfigSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanScItemSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanStatScItemSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SendHistoryRecordSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SendMailSDO;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.lattice2.epoch.sdk.oss.EpochOssService;
import com.aliyun.oss.model.ObjectMetadata;
import com.epoch.app.bcorder.contants.BcOrderConstants;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByIdsRequest;
import com.epoch.app.bcorder.model.dto.BatchQueryCompanyRequest;
import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.model.dto.SearchScItemRequest;
import com.epoch.app.bcorder.model.enums.NoticeTitle;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class SalesPlanAdjustDetailFileRepositoryImpl implements SalesPlanAdjustDetailFileRepository {
    Log log = Log.getLogger(SalesPlanAdjustDetailFileRepositoryImpl.class);

    @Resource
    private SalesPlanScItemStatRepository salesPlanScItemStatRepository;

    @Resource
    private NotificationConfigRepository notificationConfigRepository;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private SalesPlanQueryService salesPlanQueryService;

    @Resource
    private BcOrderService bcOrderService;

    @Resource
    private SendHistoryRecordRepository sendHistoryRecordRepository;

    @Resource
    private EpochOssService epochOssService;

    @Resource
    private SalesPlanRepository salesPlanRepository;

    @Resource
    private SalesPlanWriteService salesPlanWriteService;

    @Resource
    private SalesPlanScItemRepository salesPlanScItemRepository;

    /**
     * 客户地址page_size
     */
    private static final Integer CUSTOMER_ADDRESS_PAGE_SIZE = 500;

    @Override
    @RepositoryInvoker(printLog = true)
    public Result<SendMailSDO> adjustmentWriteEasyExcelFile(PageQueryAdjustmentDetailsRequest pageQueryAdjustmentDetailsRequest) {
        PageQueryPlanScItemStatRequest pageQueryPlanScItemStatRequest = new PageQueryPlanScItemStatRequest();
        BeanUtils.copyProperties(pageQueryAdjustmentDetailsRequest, pageQueryPlanScItemStatRequest);
        // 获取月度计划
        SalesPlanSDO salesPlanSDO = fetchSalesPlan(pageQueryAdjustmentDetailsRequest.getPlanId());
        // 获取调整记录
        PageResult<List<SalesPlanStatScItemSDO>> queryAdjustStatRecordResult = fetchAdjustRecord(pageQueryPlanScItemStatRequest);
        // 校验调整任务
        PageResult<List<SalesPlanSDO>> adjustPageResult = checkAdjustPlan(String.valueOf(salesPlanSDO.getId()));
        // 邮件配置
        PageResult<List<NotificationConfigSDO>> pageQuery = fetchMailConfig(salesPlanSDO);
        // 获取planTime
        String planTime = buildPlanTime(salesPlanSDO);
        // 构造发送数据
        List<MonthlyPlanDataSDO> excelList = buildMonthlyPlanDataSDO(pageQueryPlanScItemStatRequest, queryAdjustStatRecordResult, planTime, salesPlanSDO);
        // 获取文件名字
        String fileName = getFileName();
        // 上传oss
        notificationConfigRepository.generateExcel(excelList, fileName, planTime);
        // 获取下载链接存取
        extracted(pageQueryAdjustmentDetailsRequest, fileName, salesPlanSDO, planTime);
        // 变更调整任务状态
        editAdjustPlan(adjustPageResult);
        // 删除临时文件
        deleteFile(fileName);
        // 保存发送记录
        List<SendMailSDO> sendMailSDOS = saveSendRecord(pageQuery, planTime, salesPlanSDO);
        return Result.success(sendMailSDOS.get(0));
    }

    private void editAdjustPlan(PageResult<List<SalesPlanSDO>> pageResult) {
        SalesPlanSDO salesPlanSDO = new SalesPlanSDO();
        salesPlanSDO.setId(pageResult.getContent().get(0).getId());
        salesPlanSDO.setStatus(SalesPlanStatusEnum.ADJUSTED_TO_BE_REPLIED.getCode());
        salesPlanSDO.setGmtModified(new Date());
        salesPlanRepository.editSalesPlan(salesPlanSDO);
    }

    private PageResult<List<SalesPlanStatScItemSDO>> fetchAdjustRecord(PageQueryPlanScItemStatRequest request) {
        PageResult<List<SalesPlanStatScItemSDO>> listPageResult = salesPlanScItemStatRepository.pageQueryPlanScItemList(request);
        if (null == listPageResult || listPageResult.getTotal() < 1) {
            throw new FacadeException(ErrorMessage.code("OTS-02-002-02-15-026"));
        }
        return listPageResult;
    }

    private String getFileName() {
        long time = System.currentTimeMillis();
        return "月度计划数据" + time + ".xlsx";
    }

    /**
     * 删除单个文件
     *
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    private boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                log.info("删除临时文件{}成功", fileName);
                return true;
            } else {
                log.error("删除文件{}失败", fileName);
                return false;
            }
        } else {
            log.error("{}文件不存在", fileName);
            return false;
        }
    }

    private PageResult<List<NotificationConfigSDO>> fetchMailConfig(SalesPlanSDO load) {
        PageQueryNotificationConfigRequest pageQueryNotificationConfigRequest = new PageQueryNotificationConfigRequest();
        pageQueryNotificationConfigRequest.setBusinessUnitCode(load.getOrgBusinessUnitCode());
        pageQueryNotificationConfigRequest.setTitle(NoticeTitle.Plan_Adjustment.getValue().toString());
        // 兼容接口
        pageQueryNotificationConfigRequest.setBizId(load.getOrgBusinessUnitCode());
        pageQueryNotificationConfigRequest.setBizType(OrganizationTypeEnum.COMPANY.getCode());
        PageResult<List<NotificationConfigSDO>> pageQuery = notificationConfigRepository.pageQuery(pageQueryNotificationConfigRequest);
        if (null == pageQuery || pageQuery.getTotal() < 1) {
            throw new RepositoryException(ErrorMessage.code("OTS-02-005-00-16-013"));
        }

        //判断该邮件状态是否是启用状态  如果是禁用 需要提示该模板以禁用，如需使用请启用
        if (pageQuery.getContent().get(0).getStatus().equals(0)) {
            throw new FacadeException("OTS-01-001-01-15-022");
        }
        return pageQuery;
    }

    private SalesPlanSDO fetchSalesPlan(String planId) {
        QuerySalesPlanRequest querySalesPlanRequest = new QuerySalesPlanRequest();
        if (StringUtil.isNotEmpty(planId)) {
            querySalesPlanRequest.setId(planId);
        }
        Result<SalesPlanSDO> load = salesPlanQueryService.getSalesPlan(querySalesPlanRequest);
        if (Objects.isNull(load) || null == load.getResult()) {
            throw new FacadeException("OTS-02-002-00-16-001");
        }
        return load.getResult();
    }

    private String buildPlanTime(SalesPlanSDO load) {
        if (StringUtils.isNotBlank(load.getFormatPlanTime())) {
            return load.getFormatPlanTime();
        }
        String planTime = "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月");
            Date parse = sdf.parse(load.getPlanTime());
            planTime = format.format(parse);
        } catch (Exception e) {
            log.error("月度计划转日期失败", e);
        }
        return planTime;
    }

    private List<SendMailSDO> saveSendRecord(PageResult<List<NotificationConfigSDO>> pageQuery, String planTime, SalesPlanSDO load) {
        List<SendMailSDO> sendMailSDOS = pageQuery.getContent().stream().map(notificationConfigSDO -> {
            SendMailSDO sendMailSDO = new SendMailSDO();
            if (notificationConfigSDO.getTitle().equals("1")) {
                if (!notificationConfigSDO.getStatus().equals(1)) {
                    throw new FacadeException("OTS-02-005-00-15-016");
                }
                sendMailSDO.setPlanTime(planTime);
                String contents = MessageFormat.format(notificationConfigSDO.getContent(), planTime, load.getUrl());
                sendMailSDO.setContent(contents);
                sendMailSDO.setName(notificationConfigSDO.getName());
                sendMailSDO.setRecipient(notificationConfigSDO.getRecipient());
                sendMailSDO.setTitle(notificationConfigSDO.getTitle());
                sendMailSDO.setLabel(notificationConfigSDO.getLabel());
                sendMailSDO.setUrl(load.getUrl());
            }
            return sendMailSDO;
        }).collect(Collectors.toList());

        List<NotificationConfigSDO> queryContent = pageQuery.getContent();
        for (NotificationConfigSDO notificationConfig : queryContent) {
            //发送 添加进入发送记录当中
            SendHistoryRecordSDO sendHistoryRecordSDO = new SendHistoryRecordSDO();
            sendHistoryRecordSDO.setNotificationId(String.valueOf(notificationConfig.getId()));
            sendHistoryRecordSDO.setLabel(notificationConfig.getLabel());
            sendHistoryRecordSDO.setTitle(notificationConfig.getTitle());
            sendHistoryRecordSDO.setSendMethod(1);
            sendHistoryRecordSDO.setSendTime(new Date());
            sendHistoryRecordSDO.setRecipient(notificationConfig.getRecipient());
            if (CollectionUtils.isEmpty(sendMailSDOS)) {
                sendHistoryRecordSDO.setStatus(0);
            }
            sendHistoryRecordSDO.setStatus(1);
            sendHistoryRecordSDO.setAttachmentUrl(load.getUrl());
            sendHistoryRecordRepository.save(sendHistoryRecordSDO);
        }
        return sendMailSDOS;
    }

    private List<MonthlyPlanDataSDO> buildMonthlyPlanDataSDO(PageQueryPlanScItemStatRequest request, PageResult<List<SalesPlanStatScItemSDO>> queryAdjustStatRecordResult, String planTime, SalesPlanSDO salesPlanSDO) {
        SalesPlanFeatures salesPlanFeatures = salesPlanRepository.convertSalesPlanFeatures(salesPlanSDO.getFeatures());

        List<MonthlyPlanDataSDO> excelList = Lists.newArrayList();
        // TODO 逻辑待优化
        int totalPage = (queryAdjustStatRecordResult.getTotal() + CUSTOMER_ADDRESS_PAGE_SIZE - 1) / CUSTOMER_ADDRESS_PAGE_SIZE;
        for (int i = 1; i <= totalPage; i++) {
            request.setSize(CUSTOMER_ADDRESS_PAGE_SIZE);
            request.setPage(i);
            PageResult<List<SalesPlanStatScItemSDO>> listPageResult2 = salesPlanScItemStatRepository.pageQueryPlanScItemList(request);
            List<MonthlyPlanDataSDO> collect = listPageResult2.getContent().stream().map(planScItem -> {
                MonthlyPlanDataSDO monthlyPlanDataSDO = new MonthlyPlanDataSDO();
                monthlyPlanDataSDO.setPlanTime(planTime);
                monthlyPlanDataSDO.setFormatCode(11);
                monthlyPlanDataSDO.setOrgSalesOrganizationCode(salesPlanFeatures.getSubmitSalesOrgCode());

                // 通过业务单元id获取公司外部code
                BaselineGetOrganizationByIdsRequest byIdRequest = BaselineGetOrganizationByIdsRequest.builder()
                        .ids(Lists.newArrayList(salesPlanSDO.getOrgBusinessUnitCode())).status(1)
                        .build();
                Object obj = baseDataService.baselineGetOrganizationByIds(byIdRequest);

                JSONObject o = JSONObject.parseObject(JSONObject.toJSONString(obj));
                if (o != null) {
                    JSONArray array = o.getJSONArray("result");
                    if (array.size() > 0) {
                        JSONObject j = array.getJSONObject(0).getJSONObject("organizationSDO");
                        monthlyPlanDataSDO.setOrgBusinessUnitName(j.get("name").toString());
                    }
                }

                if (Objects.nonNull(obj)) {
                    Map company = convertBatchOrg(obj);
                    String outCode = (String) company.get("outCode");
                    String outName = (String) company.get("name");
                    monthlyPlanDataSDO.setCustomerName(outName);
                    monthlyPlanDataSDO.setCustomerCode(outCode);
                }
                // 获取内外部物料编码的对应关系（内部编码:外部编码）
                SearchScItemRequest searchScItemRequest = new SearchScItemRequest();
                Map<String, Object> searchReqDTO = new HashMap<>();
                List<String> scItemIdList = new ArrayList<>();
                scItemIdList.add(planScItem.getScItemId());
                searchReqDTO.put("scItemIds", scItemIdList);
                searchScItemRequest.setSearchReqDTO(searchReqDTO);
                Result<List<ScItemSDO>> searchScItem = baseDataService.searchScItem(searchScItemRequest);
                List<ScItemSDO> searchScItemResult = searchScItem.getResult();
                for (ScItemSDO scItemSDO : searchScItemResult) {
                    monthlyPlanDataSDO.setScItemName(scItemSDO.getTitle());
                    monthlyPlanDataSDO.setScItemCode(scItemSDO.getOuterId());
                }
                monthlyPlanDataSDO.setAdjustCount(planScItem.getAdjustCount());
                monthlyPlanDataSDO.setMonthFirstAdjustCount(planScItem.getMonthFirstAdjustCount());
                monthlyPlanDataSDO.setMonthMiddleAdjustCount(planScItem.getMonthMiddleAdjustCount());
                monthlyPlanDataSDO.setMonthLastAdjustCount(planScItem.getMonthLastAdjustCount());
                return monthlyPlanDataSDO;
            }).collect(Collectors.toList());

            SalesPlanScItemPageQueryRequest salesPlanScItemPageQueryRequest = new SalesPlanScItemPageQueryRequest();
            salesPlanScItemPageQueryRequest.setOrgBusinessUnitCode(salesPlanSDO.getOrgBusinessUnitCode());
            PageResult<List<SalesPlanScItemSDO>> planScItemList = salesPlanScItemRepository.pageQuerySalesPlanScItemList(salesPlanScItemPageQueryRequest);
            if (Objects.isNull(planScItemList) || CollectionUtils.isEmpty(planScItemList.getContent())) {
                throw new FacadeException("OTS-02-001-00-15-005");
            }
            List<SalesPlanScItemSDO> content = planScItemList.getContent();
            Set<Long> outBoundPriceSet = new HashSet<>();
            for (SalesPlanScItemSDO salesPlanScItemSDO : content) {
                if (salesPlanScItemSDO.getOutboundPrice() != null) {
                    outBoundPriceSet.add(salesPlanScItemSDO.getOutboundPrice());
                }
            }
            if (CollectionUtils.isEmpty(outBoundPriceSet)) {
                //如果最后全是空的情况 那么存入一个0表示 到岸价为0
                outBoundPriceSet.add(0L);
            }
            //Set<Long> outBoundPriceSet = content.stream().map(SalesPlanScItemSDO::getOutboundPrice).collect(Collectors.toSet());
            //取出最大值
            Long outBoundPriceMax = Collections.max(outBoundPriceSet);
            double doubleValue = outBoundPriceMax.doubleValue() / 100.00;
            DecimalFormat df = new DecimalFormat("#0.00");

            for (MonthlyPlanDataSDO monthlyPlanDataSDO : collect) {
                //上旬
                MonthlyPlanDataSDO monthlyPlanDataSDONew1 = new MonthlyPlanDataSDO();
                BeanUtils.copyProperties(monthlyPlanDataSDO, monthlyPlanDataSDONew1);
                Integer monthFirstAdjustCount = monthlyPlanDataSDO.getMonthFirstAdjustCount();
                monthlyPlanDataSDONew1.setDayType("S");
                monthlyPlanDataSDONew1.setAdjustReportingVolume(monthFirstAdjustCount);
                monthlyPlanDataSDONew1.setOutboundPrice(String.valueOf(df.format(doubleValue)));
                long AdjustReportingMoney1 = monthlyPlanDataSDONew1.getAdjustReportingVolume().longValue();
                monthlyPlanDataSDONew1.setAdjustReportingMoney(String.valueOf(df.format(doubleValue * AdjustReportingMoney1)));
                //中旬
                MonthlyPlanDataSDO monthlyPlanDataSDONew2 = new MonthlyPlanDataSDO();
                BeanUtils.copyProperties(monthlyPlanDataSDO, monthlyPlanDataSDONew2);
                Integer monthMiddleAdjustCount = monthlyPlanDataSDO.getMonthMiddleAdjustCount();
                monthlyPlanDataSDONew2.setDayType("Z");
                monthlyPlanDataSDONew2.setAdjustReportingVolume(monthMiddleAdjustCount);
                monthlyPlanDataSDONew2.setOutboundPrice(String.valueOf(df.format(doubleValue)));
                long AdjustReportingMoney2 = monthlyPlanDataSDONew2.getAdjustReportingVolume().longValue();
                monthlyPlanDataSDONew2.setAdjustReportingMoney(String.valueOf(df.format(doubleValue * AdjustReportingMoney2)));
                //下旬
                MonthlyPlanDataSDO monthlyPlanDataSDONew3 = new MonthlyPlanDataSDO();
                BeanUtils.copyProperties(monthlyPlanDataSDO, monthlyPlanDataSDONew3);
                Integer monthLastAdjustCount = monthlyPlanDataSDO.getMonthLastAdjustCount();
                monthlyPlanDataSDONew3.setDayType("X");
                monthlyPlanDataSDONew3.setAdjustReportingVolume(monthLastAdjustCount);
                monthlyPlanDataSDONew3.setOutboundPrice(String.valueOf(df.format(doubleValue)));
                long AdjustReportingMoney3 = monthlyPlanDataSDONew3.getAdjustReportingVolume().longValue();
                monthlyPlanDataSDONew3.setAdjustReportingMoney(String.valueOf(df.format(doubleValue * AdjustReportingMoney3)));
                if (monthlyPlanDataSDONew1.getAdjustReportingVolume() != 0) {
                    excelList.add(monthlyPlanDataSDONew1);
                }
                if (monthlyPlanDataSDONew2.getAdjustReportingVolume() != 0) {
                    excelList.add(monthlyPlanDataSDONew2);
                }
                if (monthlyPlanDataSDONew3.getAdjustReportingVolume() != 0) {
                    excelList.add(monthlyPlanDataSDONew3);
                }
            }
        }
        return excelList;
    }

    private PageResult<List<SalesPlanSDO>> checkAdjustPlan(String planId) {
        // 更新调整任务状态
        PageQuerySalePlanRequest pageQuerySalePlanRequest = new PageQuerySalePlanRequest();
        pageQuerySalePlanRequest.setParentId(planId);
        pageQuerySalePlanRequest.setModel(SalesPlanModelEnum.ADJUST_MODEL.getModel());
        pageQuerySalePlanRequest.setDir("id");
        pageQuerySalePlanRequest.setAsc(false);
        PageResult<List<SalesPlanSDO>> pageResult = salesPlanRepository.pageQuery(pageQuerySalePlanRequest);
        if (null == pageResult || pageResult.getTotal() < 1) {
            throw new RepositoryException(ErrorMessage.code("OTS-02-005-00-16-011"));
        }
        SalesPlanSDO salesPlanSDO = pageResult.getContent().get(0);
        if (SalesPlanStatusEnum.ADJUST.getCode().equals(salesPlanSDO.getStatus()) || SalesPlanStatusEnum.ADJUSTED_TO_BE_REPLIED.getCode().equals(salesPlanSDO.getStatus())) {
            return pageResult;
        } else {
            throw new RepositoryException(ErrorMessage.code("OTS-02-005-00-16-014"));
        }
    }

    private void extracted(PageQueryAdjustmentDetailsRequest pageQueryAdjustmentDetailsRequest, String fileName, SalesPlanSDO load, String planTime) {
      /*  SimpleDateFormat str = new SimpleDateFormat("yyyy-MM");
        Date date = new Date();
        String format = str.format(date);*/
        ObjectMetadata metadata = new ObjectMetadata();
        try {
            // 获取oss链接
            log.info("获取文件url下载链接oss信息:{}，{}", BcOrderConstants.OSS_NAME(), BcOrderConstants.OSS_BUCKET());
            URL oss = epochOssService.getPresignedUrl(BcOrderConstants.OSS_NAME(), BcOrderConstants.OSS_BUCKET(), "salesPlan/adjustFile/" + planTime, fileName, 2592000000L);
            log.info("获取文件url下载链接结果:{}", JSONObject.toJSONString(oss));
            // 更新url
            SalesPlanSDO sdo = new SalesPlanSDO();
            sdo.setId(load.getId());
            sdo.setEstimateDiscount(load.getEstimateDiscount());
            sdo.setMonthFirstProprtion(load.getMonthFirstProprtion());
            sdo.setMonthMiddleProprtion(load.getMonthMiddleProprtion());
            sdo.setMonthLastProprtion(load.getMonthLastProprtion());
            sdo.setPlanNotice(load.getPlanNotice());
            sdo.setMonthFirst(load.getMonthFirst());
            sdo.setMonthMiddle(load.getMonthMiddle());
            sdo.setMonthLast(load.getMonthLast());
            String url = oss.toString().replace("http://", "https://");
            sdo.setUrl(url);
            load.setUrl(url);
            salesPlanWriteService.editSalesPlan(sdo);
        } catch (Exception e) {
            log.error("获取oss url发生异常", e);
            throw new RepositoryException(ErrorMessage.code("OTS-02-005-00-16-012"));
        }
    }

    private Map convertBatchOrg(Object obj) {
        JSONObject o = JSONObject.parseObject(JSONObject.toJSONString(obj));
        if (o != null) {
            JSONArray array = o.getJSONArray("result");
            if (array.size() > 0) {
                JSONObject j = array.getJSONObject(0).getJSONObject("organizationSDO");
                String bidId = (String) j.get("bizId");
                BatchQueryCompanyRequest companyRequest = BatchQueryCompanyRequest.builder().ids(Lists.newArrayList(bidId)).build();
                Map map = (Map) bcOrderService.batchQueryCompany(companyRequest);
                Map result = (Map) map.get("result");
                List<Map> content = (List<Map>) result.get("content");
                Map company = content.get(0);
                return company;
            }
        }
        return null;
    }

}
